(function () {
    angular.module('app')
        .factory('DrugInfoFactory',fn);

    //var localPersonInfo = {};
    function fn(urlCnst,mockHttp,userService) {
        var self = {};

        self.getDrugInfoById = function (drugId, cb){
            // 后端暂无药品信息
            // if( !urlCnst['mockHttp'] ){
            //     urlCnst.get('somepath',cb);
            //     return;
            // }
            var drug = mockHttp.allDrug;
            var result = {msg:'',err:0,res:[]};
            for ( var i=0; i<drug['res'].length; i++ ){
                if ( drug['res'][i]['drugId'] == drugId ) result['res'].push(drug['res'][i]);
            }
            return cb(result['err'],result);
        };

        function existDrug (item, list){
            for (var i=0; i<list.length; i++){
                if (item['drugId'] === list[i]['drugId'])
                    return i;
            }
            return -1;
        }

        self.postDrugInCart = function (userId, drugId, body, cb) {
            if( !urlCnst['mockHttp'] ){
                urlCnst.post('carts/user/'+ userId +'/drug/'+ drugId, body, cb);
            }
            else {
                var position = existDrug(body, userService.drugInCart);
                if (position > -1){
                    userService.drugInCart[position]['number'] += body['number'];
                } else {
                    userService.drugInCart.push(body);
                }
                return cb(0,body);
            }
        };
        return self;
    }
})();
